﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Hosting;
using MySqlX.XDevAPI.Common;
using Renci.SshNet.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.Web.Filter
{
    /// <summary>
    /// 异常捕获过滤，捕获所有异常情况信息
    /// </summary>
    public class ExceptionFilter : Attribute, IExceptionFilter
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IModelMetadataProvider _modelMetadataProvider;

        public ExceptionFilter(IWebHostEnvironment webHostEnvironment, IModelMetadataProvider modelMetadataProvider)
        {
            _webHostEnvironment = webHostEnvironment;
            _modelMetadataProvider = modelMetadataProvider;
        }


        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                if (_webHostEnvironment.IsDevelopment()) //如果是开发环境
                {
                    var result = new ViewResult { ViewName = "../Error" };
                    result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState);
                    result.ViewData.Add("Exception", context.Exception);//传递异常数据
                    context.Result = result;
                }
                else
                {
                    context.Result = new JsonResult(new { 
                        Result=false,
                        Code=500,
                        Message= context.Exception.Message
                    });
                }
                context.ExceptionHandled = true;  //异常已处理
            }
        }
    }
}
